import React, { useState } from "react";
import {
  Card,
  Typography,
  Space,
  Switch,
  Divider,
  Button,
  Row,
  Col,
  Tag,
  Alert,
} from "antd";
import TreeView, { TreeNodeData } from "../components/TreeView";
import Icon from "../utils/icons";

const { Title, Paragraph, Text } = Typography;

// 异步加载根节点数据
const rootTreeData: TreeNodeData[] = [
  {
    key: "1",
    title: "根节点1（点击展开，加载子节点）",
    icon: "Folder",
  },
  {
    key: "2",
    title: "根节点2（点击展开，加载子节点）",
    icon: "Folder",
  },
  {
    key: "3",
    title: "根节点3（点击展开，加载子节点）",
    icon: "Folder",
  },
];

/**
 * 树形控件示例页面 - 精简版
 * 主要展示异步加载和多选功能
 */
const TreeViewDemo: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [checkable, setCheckable] = useState(true);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [checkStrictly, setCheckStrictly] = useState(false);
  const [expandLog, setExpandLog] = useState<string[]>([]);

  // 异步加载子节点
  const loadData = async (node: TreeNodeData): Promise<TreeNodeData[]> => {
    // 模拟网络请求延迟
    setLoading(true);

    // 记录加载日志
    setExpandLog((prev) => [
      ...prev,
      `正在加载节点 "${node.title}" 的子节点...`,
    ]);

    return new Promise((resolve) => {
      setTimeout(() => {
        // 根据节点ID生成不同数量的子节点
        const childCount = parseInt(node.key) * 2;
        const children = Array.from({ length: childCount }).map((_, index) => ({
          key: `${node.key}-${index + 1}`,
          title: `子节点 ${node.key}-${index + 1}`,
          icon: index % 2 === 0 ? "Folder" : "File",
          isLeaf: index % 2 !== 0, // 偶数索引为文件夹，奇数索引为文件
        }));

        // 记录加载完成日志
        setExpandLog((prev) => [
          ...prev,
          `节点 "${node.title}" 的 ${childCount} 个子节点加载完成`,
        ]);
        setLoading(false);
        resolve(children);
      }, 1000);
    });
  };

  // 处理节点展开/折叠
  const handleExpand = (node: TreeNodeData, expanded: boolean) => {
    const action = expanded ? "展开" : "收起";
    const log = `${action}节点: ${node.title}`;
    setExpandLog((prev) => [...prev, log]);
    console.log(log);
  };

  // 处理复选框变化
  const handleCheck = (checked: string[], info: any) => {
    console.log("选中的节点:", checked);
    console.log("半选中的节点:", info.halfCheckedKeys);
    setCheckedKeys(checked);
  };

  return (
    <div style={{ padding: "24px" }}>
      <Title level={2}>异步加载与多选树形控件</Title>
      <Paragraph>
        简化版树形控件，仅保留异步加载和多选功能，用于展示层级数据。
      </Paragraph>

      <Alert
        message="操作指引"
        description="点击文件夹图标左侧的箭头可以异步加载子节点。已加载的节点会保持状态，即使展开/收起操作也不会丢失子节点数据。"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Row gutter={[24, 24]}>
        <Col xs={24} lg={8}>
          <Card title="配置选项">
            <Space direction="vertical" style={{ width: "100%" }}>
              <div>
                <Text>启用多选:</Text>
                <Switch
                  checked={checkable}
                  onChange={setCheckable}
                  style={{ marginLeft: 8 }}
                />
              </div>

              {checkable && (
                <>
                  <div>
                    <Text>父子节点独立选择:</Text>
                    <Switch
                      checked={checkStrictly}
                      onChange={setCheckStrictly}
                      style={{ marginLeft: 8 }}
                    />
                    <div style={{ marginTop: 4, fontSize: 12, color: "#888" }}>
                      {checkStrictly
                        ? "选中父节点不会自动选中子节点"
                        : "选中父节点会自动选中所有子节点"}
                    </div>
                  </div>

                  <div>
                    <Button onClick={() => setCheckedKeys([])}>清除选中</Button>
                  </div>
                </>
              )}

              <Divider />

              <div>
                <Text strong>操作日志:</Text>
                <div
                  style={{
                    marginTop: 8,
                    maxHeight: 200,
                    overflow: "auto",
                    padding: 8,
                    background: "#f5f5f5",
                    borderRadius: 4,
                    fontSize: 12,
                  }}
                >
                  {expandLog.length === 0 ? (
                    <Text type="secondary">暂无操作</Text>
                  ) : (
                    <ul style={{ paddingLeft: 20, margin: 0 }}>
                      {expandLog.map((log, index) => (
                        <li key={index}>
                          <Text>{log}</Text>
                        </li>
                      ))}
                    </ul>
                  )}
                </div>
                <Button
                  type="text"
                  size="small"
                  onClick={() => setExpandLog([])}
                  disabled={expandLog.length === 0}
                >
                  清空日志
                </Button>
              </div>
            </Space>
          </Card>
        </Col>

        <Col xs={24} lg={16}>
          <Card
            title={
              loading ? (
                <span>
                  异步加载树 <Tag color="processing">加载中...</Tag>
                </span>
              ) : (
                "异步加载树"
              )
            }
          >
            <div
              style={{
                height: 400,
                overflow: "auto",
                border: "1px solid #f0f0f0",
                padding: 8,
                borderRadius: 4,
              }}
            >
              <TreeView
                treeData={rootTreeData}
                loadData={loadData}
                onExpand={handleExpand}
                checkable={checkable}
                checkedKeys={checkedKeys}
                onCheck={handleCheck}
                checkStrictly={checkStrictly}
              />
            </div>

            {checkable && (
              <div style={{ marginTop: 16 }}>
                <div>当前选中节点：{checkedKeys.length} 个</div>
                {checkedKeys.length > 0 && (
                  <div style={{ marginTop: 8 }}>
                    <Space wrap>
                      {checkedKeys.map((key) => (
                        <Tag key={key} color="blue">
                          {key}
                        </Tag>
                      ))}
                    </Space>
                  </div>
                )}
              </div>
            )}
          </Card>
        </Col>
      </Row>

      <Divider />

      <Card title="使用说明">
        <Title level={4}>基本用法</Title>
        <pre style={{ background: "#f5f5f5", padding: 16, borderRadius: 4 }}>
          {`import TreeView from '@/components/TreeView';

// 异步加载子节点
<TreeView
  treeData={rootData}
  loadData={(node) => fetchChildren(node.key)}
  onExpand={(node, expanded) => console.log(expanded ? '展开' : '收起', node)}
/>

// 多选模式
<TreeView
  treeData={treeData}
  checkable
  checkedKeys={checkedKeys}
  onCheck={(checked, info) => setCheckedKeys(checked)}
/>`}
        </pre>
      </Card>
    </div>
  );
};

export default TreeViewDemo;
